package com.element.security.constant;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @auther zhangwj
 * @date 2021/3/18 下午8:10
 */
public enum AuthGrantTypeEnum {

    AUTHORIZATION_CODE(1, "authorization_code"),
    PASSWORD(2, "password"),
    REFRESH_TOKEN(3, "refresh_token"),
    IMPLICIT(4, "implicit"),
    CLIENT_CREDENTIALS(5, "client_credentials");

    public static Set<String> getAuthGrantType(List<Integer> types) {
        Set<String> authGrantTypes = new HashSet<>();
        if (null == types || types.isEmpty()) {
            return authGrantTypes;
        }
        for (AuthGrantTypeEnum authGrantTypeEnum : AuthGrantTypeEnum.values()) {
            for (Integer type : types) {
                if (authGrantTypeEnum.getType().equals(type)) {
                    authGrantTypes.add(authGrantTypeEnum.getGrantType());
                }
            }
        }
        return authGrantTypes;
    }

    public static String getList(int... types) {
        List<Integer> typeList = new ArrayList<>(types.length);
        for (Integer type : types) {
            typeList.add(type);
        }
        return JSON.toJSONString(typeList);
    }

    public static boolean hasType(String grantType) {
        if (StringUtils.isEmpty(grantType)) {
            return false;
        }
        for (AuthGrantTypeEnum authGrantTypeEnum : AuthGrantTypeEnum.values()) {
            if (grantType.equals(authGrantTypeEnum.getGrantType())) {
                return true;
            }
        }
        return false;
    }

    public static Map<Integer, String> getGrantTypeMap() {
        Map<Integer, String> map = new HashMap<>();
        for (AuthGrantTypeEnum authGrantTypeEnum : AuthGrantTypeEnum.values()) {
            map.put(authGrantTypeEnum.getType(), authGrantTypeEnum.getGrantType());
        }
        return map;
    }

    AuthGrantTypeEnum(Integer type, String grantType) {
        this.type = type;
        this.grantType = grantType;
    }

    private final Integer type;

    private final String grantType;

    public Integer getType() {
        return type;
    }

    public String getGrantType() {
        return grantType;
    }
}
